package com.qibao.toolkit.exception.strategy;

import com.qibao.toolkit.web.ResponseModel;
import org.apache.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangcheng
 * @version $Id: AbstractExceptionHandleStrategy.java, v0.1 2018/9/27 14:39 wangcheng Exp $$
 */
public abstract class AbstractExceptionHandleStrategy implements ExceptionHandleStrategy {

    @Override
    public ResponseModel handle(HttpServletRequest request, HttpServletResponse response, Throwable throwable) {
        preHandle(request, response, throwable);
        return doHandle(throwable);
    }


    /**
     * 预处理异常信息
     */
    private void preHandle(HttpServletRequest request, HttpServletResponse response, Throwable throwable) {
        request.removeAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
        response.setStatus(HttpStatus.SC_OK);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    }

    /**
     * 执行异常处理逻辑
     * @param throwable
     * @return
     */
    public abstract ResponseModel doHandle(Throwable throwable);


    @Override
    public String toString() {
        return this.getClass().getName();
    }

}
